package com.atguigu.java.test1;


import org.junit.Test;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * UDP协议的网络编程
 *
 * @author shkstart
 * @create 2021-02-01 21:55
 */
public class UDPTest {
    @Test
    //发送端
    public void sender() {

        DatagramSocket scoket = null;
        try {
            scoket = new DatagramSocket();

            //封装数据
            String str = "好好学习";
            byte[] bytes = str.getBytes();
            InetAddress in1 = InetAddress.getLocalHost();
            DatagramPacket dp = new DatagramPacket(bytes, 0, bytes.length, in1, 1010);
            scoket.send(dp);
            System.out.println("发送完成");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (scoket != null) {

                    scoket.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


    }


    @Test
    //接收端
    public void receiver() {
        DatagramSocket socket = null;
        try {
            socket = new DatagramSocket(1010);
            byte[] bytes = new byte[1010];
            DatagramPacket dp = new DatagramPacket(bytes, 0, bytes.length);
            socket.receive(dp);
            System.out.println(new String(dp.getData(), 0, dp.getLength()));
            System.out.println("接收成功");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (socket != null)
                    socket.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


    }

}
